package com.itheima.aop;

import com.itheima.common.LogInfo;
import com.itheima.common.ResultResponse;
import com.itheima.dao.LogMapper;
import com.itheima.domain.Log;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author itheima
 * @Date 2022/4/26 17:54
 * 日志切面类2个部分构成
 * 1.切入点
 * 2.环绕通知
 */
@Aspect
@Component
public class LogAspect {
    @Autowired
    LogMapper logMapper;


    //1.切入点：表达式找到要被增强的方法
    @Pointcut("execution(* com.itheima.controller.*.*(..))")
    public void myPoint() {
    }

    //2.环绕通知
    @Around("myPoint()")
    public ResultResponse log(ProceedingJoinPoint joinPoint) throws Throwable {
        //1.获取系统操作时间Date date=new Date();  SimpleDateFormat
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
        String operateTime = sdf.format(new Date());

        //2.获取 @LogInfo(operateDesc = "根据主键查询用户")
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        LogInfo logInfo = method.getAnnotation(LogInfo.class);
        String operateDesc = logInfo.operateDesc();

        //3.获取 目标方法queryUser所在类以及方法名
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();

        ResultResponse response = (ResultResponse) joinPoint.proceed();
        //4.获取目标方法返回的结果：ResultResponse(200, "操作成功", user);
        String operateResult = response.getMessage();

        //最后：创建日志对象，然后 插入日志表
        logMapper.insert(new Log(null, "大兵哥", operateDesc + ":" + className + "." + methodName, operateTime, operateResult));
        return response;
    }
}
